
/**
 * @file index.js
 * @author swan
 */
const app = getApp()
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var bdApi = require('../../utils/bdApi.js');
var bdRequest = require('../../utils/bdRequest.js')
import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var WxParse = require('../../wxParse/wxParse.js');
import seoConfig from '../../seoConfig/config.js'
Page({
    data: {
        postsList: [],
        isLastPage: false,
        page: 1,
        categories: 0,
        showCategoryName: "",
        categoryName: "",
        displaySwiper: "none",
        userInfo: {},
        hasUserInfo: false,
        postsShowSwiperList: [],
        current: 0,
        switchAutoPlayStatus: true,
        switchDuration: 500,
        autoPlayInterval: 2000,
        switchIndicateStatus: true,
        tabs: ['最新文章', '档案查询', '档案百科', '死档激活'],
        name: '',
        stv: {
            windowWidth: 0,
            lineWidth: 0,
            offset: 0,
            tStart: false
        },
        activeTab: 0,
        picnewslist: [{ url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }],
        newslist: [{ url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }, { url: 'https://www.bds110.com/wp-content/uploads/2019/04/2019040406125374.jpg', title: '档案托管怎么办理？' }],
        postsSpecialList: []
    },
    onShow: function () {
        this.setConfig(seoConfig.indexConfig)
    },
    onLoad: function (options) {
        // 监听页面加载的生命周期函数
        try {
            let { tabs } = this.data;
            // var res = swan.getSystemInfoSync()
            this.windowWidth = 670;
            this.data.stv.lineWidth = this.windowWidth / this.data.tabs.length;
            this.data.stv.windowWidth = this.windowWidth;
            this.setData({ stv: this.data.stv })
            this.tabsCount = tabs.length;

        } catch (e) {
        }
        this.fetchTopFivePosts();
        this.getCategories();
        this.fetchPostsData({ id: 100 })
        this.fetchSpecial()
    },
    contactCB(e) {
        console.log(e.detail); // 输出：{errMsg: 'enterContact:ok'}
        // 进入客服会话页面成功，可进行自己的业务逻辑
        if (e.detail.errMsg === 'enterContact:ok') {
            swan.reportAnalytics('userMessage', {
                visit: 1,
                message: '进入客服页面PV'
            });
        }
        // 可进行一些进入失败的业务逻辑
        else {
        console.log(111)
            swan.reportAnalytics('userMessage', {
                visit: 0,
                message: '进入客服页面失败损失PV'
            });
        }
    },
    setConfig(seo) {
          swan.setPageInfo({
            title: seo.title,
            keywords: seo.keywords,
            description:seo.description,
            articleTitle: seo.title,
            success: function () {
                console.log('setPageInfo success');
            },
            fail: function (err) {
                console.log('setPageInfo fail', err);
            },
            complete: function (err) {
                console.log('setPageInfo fail', err);
            }

        })
    },
    fetchSpecial() {
        var self = this
        var getPostsRequest = bdRequest.getRequest(Api.getSpecial());
        getPostsRequest.then(response => {
            // console.log(response, 'getSpecial')
            if (response.statusCode == '200' && response.data.length > 0) {
                let ids = [], urls = []
                for (let item of response.data) {
                    ids.push(item.id)
                    // urls.push(bdRequest.getRequest(Api.getSpecialListImg(item.id))) 
                    let getImgRequest = bdRequest.getRequest(Api.getSpecialListImg(item.id));
                    urls.push(getImgRequest)
                    // getImgRequest.then(res=>{
                    //     console.log(res)
                    // })
                }
                Promise.all(urls).then((result) => {
                    response.data.forEach((item, index, arr) => {
                        // console.log(result[index].data.data.thumb)
                        item.imgurl = result[index].data.data.thumb
                    })
                    let arr = []
                    response.data.forEach(function (item) {
                        if (config.getSpecial.includes(item.id)) {
                            arr.push(item);
                        }
                    })
                    self.setData({
                        postsSpecialList: self.data.postsSpecialList.concat(arr),
                    });
                }).catch((error) => {
                    console.log(error)
                })



            }
        })
    },
    fetchTopFivePosts: function () {
        var self = this;
        //取置顶的文章
        var getPostsRequest = bdRequest.getRequest(Api.getSwiperPosts());
        getPostsRequest.then(response => {
            // console.log(response)
            if (response.data.status == '200' && response.data.posts.length > 0) {
                self.setData({
                    // postsShowSwiperList: response.data.posts,
                    postsShowSwiperList: self.data.postsShowSwiperList.concat(response.data.posts.map(function (item) {
                        //item.firstImage = Api.getContentFirstImage(item.content.rendered);
                        // if (item.post_medium_image_300 == null || item.post_medium_image_300 == '') {
                        //     if (item.content_first_image != null && item.content_first_image != '') {
                        //         item.post_medium_image_300 = item.content_first_image;
                        //     }
                        //     else {
                        //         item.post_medium_image_300 = "";
                        //     }

                        // }
                        return item;
                    })),
                    displaySwiper: "block"
                });

            }
            else {
                self.setData({
                    displaySwiper: "none"
                });

            }

        }).catch(function (response) {
            //  console.log(response);
            self.setData({
                showerror: "block",
                floatDisplay: "none"
            });

        })
            .finally(function () {

            });

    },
    //获得文章分类
    getCategories() {
        var getPostsRequest = bdRequest.getRequest(Api.getCategories());
        getPostsRequest
            .then(response => {
                if (response.statusCode === 200) {
                    let tabs = response.data
                    tabs.unshift({ id: 0, name: '最新' })
                    this.setData({
                        tabs: tabs
                    })
                }
                else {

                    swan.showToast({
                        title: response.data.message,
                        duration: 1500
                    })

                }

            })
    },

    _updateSelectedPage(page) {
        let { tabs, stv, activeTab } = this.data;
        activeTab = page;
        this.setData({ activeTab: activeTab })
        stv.offset = stv.windowWidth * activeTab;
        this.setData({ stv: this.data.stv })
    },
    handlerTabTap(e) {
        this._updateSelectedPage(e.currentTarget.dataset.index);

        this.setData({
            page: 1,
            categories: e.currentTarget.dataset.id

        })
        this.fetchPostsData({
            page: 1,
            categories: e.currentTarget.dataset.id
        });
    },
    // onLoad() {

    // },
    swiperChange(e) {
        // console.log('swiperChange:', e.detail);
    },
    formSubmit: function (e) {
        console.log('form发生了submit事件，携带数据为：', e.detail.value);
        let data = e.detail.value
        if (!data.name || !data.tel || !data.school) {
            swan.showToast({
                icon: 'none',
                title: '请填写所有选项',
                duration: 1000
            });
        }
        var url = Api.postFormUrl();
        var ip = new Date().getTime() + Math.round(Math.random() * 10000); // 小程序端无法获取ip
        var content = `类&nbsp;&nbsp;型：档案查询系统\n姓&nbsp;&nbsp;名：${data.name}\n联系电话：${data.tel}\n毕业院校：${data.school}\n来源： 办得爽百度小程序`
        var postLikeRequest = bdRequest.postRequest(url, { title: "办得爽小程序-档案查询系统", tel: data.tel, name: data.name, content: content, "from": '百度小程序', ip: ip });
        postLikeRequest
            .then(response => {
                if (response.data.status == '200') {
                    swan.showToast({
                        icon: 'success',
                        title: '提交成功'
                    });
                    this.setData({
                        name: ''
                    })

                }
            })
    },
    getUserInfo(e) {
        swan.login({
            success: () => {
                swan.getUserInfo({
                    success: (res) => {
                        this.setData({
                            userInfo: res.userInfo,
                            hasUserInfo: true
                        });
                    },
                    fail: () => {
                        this.setData({
                            userInfo: e.detail.userInfo,
                            hasUserInfo: true
                        });
                    }
                });
            },
            fail: () => {
                swan.showModal({
                    title: '未登录',
                    showCancel: false
                });
            }
        });
    },
    playPhone() {
        swan.makePhoneCall({
            phoneNumber: '4009687088' //仅为示例，并非真实的电话号码
        });
    },
    //获取文章列表数据
    fetchPostsData: function (data) {
        var self = this;
        if (!data) data = {};
        if (!data.page) data.page = 1;
        if (!data.categories) data.categories = 0;
        if (!data.search) data.search = '';
        if (data.page === 1) {
            self.setData({
                postsList: []
            });
        };
        swan.showLoading({
            title: '正在加载',
            mask: true
        });
        if (data.categories === 0) {
            var getPostsRequest = bdRequest.getRequest(Api.getPosts(data));
        } else {
            var getPostsRequest = bdRequest.getRequest(Api.getPosts(data));
        }
        getPostsRequest
            .then(response => {
                if (response.statusCode === 200) {
                    for (var i = 0; i < response.data.length; i++) {
                        // console.log(response.data[i].excerpt.rendered);
                        var rendered = response.data[i].excerpt.rendered;
                        if (rendered === '') {
                            continue
                        }
                        var res = WxParse.bdParse('rendered', 'html', rendered, self, 5, true);
                        // console.log(res);
                        response.data[i].excerpt.rendered = res;
                    }
                    if (response.data.length < pageCount) {
                        self.setData({
                            isLastPage: true
                        });
                    } else {
                        self.setData({
                            isLastPage: false
                        });
                    }
                    self.setData({
                        floatDisplay: "block",
                        postsList: self.data.postsList.concat(response.data.map(function (item) {
                            var strdate = item.date
                            if (item.category_name != null) {
                                item.categoryImage = "";
                            }
                            else {
                                item.categoryImage = "";
                            }
                            if (item.post_thumbnail_image == null || item.post_thumbnail_image == '') {
                                item.post_thumbnail_image = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/logo700.png";
                            }
                            if(item.categories.length>0){
                                let aa = config.getUrlList.find(resd=>{
                                    return resd.categoryID==item.categories[0]
                                })
                               if(aa){
                                    item.h5url=aa.url
                                }else{
                                    item.h5url=''
                                }
                            }
                            item.date = util.cutstr(strdate, 10, 1);
                            // console.log(item);
                            return item;
                        })),
                    });
                    setTimeout(function () {
                        swan.hideLoading();
                    }, 900);
                }
                else {
                    if (response.data.code == "rest_post_invalid_page_number") {
                        self.setData({
                            isLastPage: true
                        });
                        swan.showToast({
                            title: '没有更多内容',
                            mask: false,
                            duration: 1500
                        });
                    }
                    else {
                        swan.showToast({
                            title: response.data.message,
                            duration: 1500
                        })
                    }
                }
            })
            .catch(function (response) {
                if (data.page == 1) {
                    self.setData({
                        showerror: "block",
                        floatDisplay: "none"
                    });

                }
                else {
                    console.log(response);
                    swan.showModal({
                        title: '加载失败',
                        content: '加载数据失败,请重试.',
                        showCancel: false,
                    });
                    self.setData({
                        page: data.page - 1
                    });
                }
            })
            .finally(function (response) {
                swan.hideLoading();
                // swan.stopPullDownRefresh();
            });
    },

    //加载分页
    loadMore: function (e) {

        var self = this;
        if (!self.data.isLastPage) {
            self.setData({
                page: self.data.page + 1
            });
            //console.log('当前页' + self.data.page);
            this.fetchPostsData(self.data);
        }
        else {
            swan.showToast({
                title: '没有更多内容',
                mask: false,
                duration: 1000
            });
        }
    },
    // 跳转至查看文章详情
    redictDetail: function (e) {
        // console.log('查看文章');
        var id = e.currentTarget.id,
            url = '../detail/detail?id=' + id;
        swan.navigateTo({
            url: url
        })
    },
    //首页图标跳转
    onNavRedirect: function (e) {
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
        var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData;
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                extraData: extraData,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }

    },
    // 跳转至查看小程序列表页面或文章详情页
    redictAppDetail: function (e) {
        console.log('查看文章');
        var id = e.currentTarget.id;
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;

        if (redicttype == 'detailpage')//跳转到内容页
        {
            url = '../detail/detail?id=' + id;
            swan.navigateTo({
                url: url
            })
        }
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }
    }
})
